<?php
class Model_DB
{
    var $host;
    var $user;
    var $password;
    var $database;
    var $database_object;
    var $res;
    var $DEBUG = false;
    
    public function __construct()
    {
        $config         = __get_config();
        $this->host     = $config['DB']['DB_SERVER'];
        $this->user     = $config['DB']['DB_USER'];
        $this->password = $config['DB']['DB_PASS'];
        $this->database = $config['DB']['DB_NAME'];
        $this->connect();
        
    }
    private function connect()
    {
        $this->database_object = mysql_connect($this->host, $this->user, $this->password);
        mysql_select_db($this->database, $this->database_object);
        mysql_query('set names utf8', $this->database_object);
    }
    public function query($sql)
    {
    	if( $this->DEBUG ) { echo "$sql<br />"; }
        $this->res = mysql_query($sql, $this->database_object);
    }
    public function fetch()
    {
        return mysql_fetch_assoc($this->res);
    }
    public function num_rows()
    {
        return mysql_num_rows($this->res);
    }
    public function escape($str)
    {
        return mysql_real_escape_string($str, $this->database_object);
    }
    public function insert($table, $data)
    {
        $f = array();
        $v = array();
        foreach($this->getFieldList($table) as $key => $_){
            if (isset($data[$key])){
                $f[] = $key;
                $v[] = ($data[$key] != ''  ? '\'' . $this->escape($data[$key]) . '\'' : 'null');
            }
            elseif($key == 'r_date' or $key == 'u_date'){
                $f[] = $key;
                $v[] = 'current_timestamp';
            }
        }
        $sql = sprintf('insert into %s ( %s ) values ( %s )', $table, implode(',', $f), implode(',', $v));
       
        $this->query($sql);
        if($this->res){
            $this->query('select last_insert_id()');
            return array_shift($this->fetch());
        }
        else{
            //echo(mysql_error());
            return false;
        }
    }
    public function replace($table, $data)
    {
        $f = array();
        $v = array();
        foreach($this->getFieldList($table) as $key => $_){
            if (isset($data[$key])){
                $f[] = $key;
                $v[] = ($data[$key] != ''  ? '\'' . $this->escape($data[$key]) . '\'' : 'null');
            }
            elseif($key == 'r_date'){
                $f[] = $key;
                $v[] = 'current_timestamp';
            }
        }
        $sql = sprintf('replace into %s ( %s ) values ( %s )', $table, implode(',', $f), implode(',', $v));
        
        $this->query($sql);
        if($this->res){
            $this->query('select last_insert_id()');
            return array_shift($this->fetch());
        }
        else{
            //echo(mysql_error());
            return false;
        }
    }
    public function update($id, $table, $data, $pri = 'id')
    {
        $u = array();
        foreach($this->getFieldList($table) as $key => $_){
            if (isset($data[$key]) && $key != $pri && $key != 'r_date' && $key != 'u_date'){
                $u[] = $key . '=' . ($data[$key] != ''  ? '\'' . $this->escape($data[$key]) . '\'' : 'null');
            }elseif( $key == 'u_date'){
            	$u[] = $key . ' = current_timestamp';
            }
        }
       
        $sql = sprintf("update %s set %s where %s = '%s'", $table, implode(',', $u), $pri, $id);
         
        $this->query($sql);
        return $this->res;
    }
    public function delete($table, $data)
    {
        $where = array();
        foreach($this->getFieldList($table) as $key => $_){
            if (isset($data[$key])){
                $where[] = $key . ($data[$key] != ''  ? ' = \'' . $this->escape($data[$key]) . '\'' : ' is null');
            }
        }
        
        $sql = sprintf("delete from %s where 1 = 1 and %s", $table, implode(' and ', $where));
       
        $this->query($sql);
        return $this->res;
    }
    //
    public function getList($table, $where = array(), $orderby = '', $limit = '', $offset = '')
    {
        $list = array();
        $sql  = "select * from {$table}" . (!empty($where) ? " where ".implode(' AND ', $where) : "") . (!empty($orderby) ? " order by {$orderby}" : "") . (!empty($limit) ? " limit {$limit}" : "") . (!empty($offset) ? " offset {$offset}" : "");
       
        $this->query($sql);
        if ($this->res){
            while($res = $this->fetch()){
                if(isset($res['id'])){
                    $list[$res['id']] = $res;
                }
                else{
                    $list[] = $res;
                }
            }
        }
        return $list;
    } 
    //
    //
    public function getFieldList($table)
    {
        $list = array();
        $this->query(sprintf('desc %s', $this->escape($table)));
        
        while($res = $this->fetch()){
            $list[$res['Field']] = $res;
        }
        return $list;
    }

    
}
?>
